home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 98 / Skunkware 98.iso / osr5 / sco / scripts / admin / chksulog < prev    next >
Encoding:
AWK Script  |  1997-08-26  |  29.1 KB  |  791 lines

  1. #!/usr/local/bin/gawk -f
  2. # @(#) chksulog.gawk 1.1 96/06/17
  3. # 95/03/16 john h. dubois iii (john@armory.com)
  4. # 96/06/17 Added RDTA options.
  5.  
  6. # sulog format:
  7. #SU 06/21 00:01 + tty?? root-adm
  8.  
  9. BEGIN {
  10.     Name = "chksulog"
  11.     Usage = "Usage:\n"\
  12. Name " [-hsu] [-[rR]<from>] [-[dD]<dest>] [-[tT]<tty>] [-[aA]<app>] [file ...]"
  13.     DefLog = "/usr/adm/sulog"
  14.     ARGC = Opts(Name,Usage,"hsur:R:d:D:t:T:a:A:",0)
  15.     if ("h" in Options) {
  16.     printf \
  17. "%s: Print interesting lines from su logfile.\n"\
  18. "%s\n"\
  19. "If no filenames are given, the standard su logging file %s is used.\n"\
  20. "Options:\n"\
  21. "-h: Print this help.\n"\
  22. "-s: Print only successful ID changes.\n"\
  23. "-u: Print only unsuccessful ID changes.\n"\
  24. "-r<req>: Print only changes requested by account <from>.\n"\
  25. "-d<dest>: Print only changes initiated to account <dest>.\n"\
  26. "-t<tty>: Print only changes initiated on tty <tty>.  Use '-' to print\n"\
  27. "    changes initiated by processes with no controlling tty.\n"\
  28. "-a<app>: Print changes initiated through app <app>, where <app> is e.g.\n"\
  29. "    su, asroot, etc.\n"\
  30. "R, D, T, and A are like r, d, t, and a, but the prevent matching lines\n"\
  31. "from being printed.  Either the lower or upper case option for each should\n"\
  32. "be used; they should not be used together.\n"\
  33. "All of the values given with the above are case insensitive and can be\n"\
  34. "patterns in the style of egrep(C).  Patterns are implicitely anchored at\n"\
  35. "the start and end.  Multiple options exclude more lines from being printed.\n"\
  36. "If none of the above are given, then only unsuccesful changes to root by\n"\
  37. "accounts other than root are printed.\n",Name,Usage,DefLog
  38.     exit(0)
  39.     }
  40.     if (ARGC == 1) {
  41.     ARGC = 2
  42.     ARGV[1] = DefLog
  43.     }
  44.     IGNORECASE = 1
  45.     Succ = "s" in Options
  46.     Unsucc = "u" in Options
  47.     if (!Succ && !Unsucc)
  48.     Succ = Unsucc = 1
  49.     if ("r" in Options) {
  50.     Req = "^(" Options["r"] ")$"
  51.     OptGiven = 1
  52.     }
  53.     if ("R" in Options) {
  54.     NotReq = "^(" Options["R"] ")$"
  55.     OptGiven = 1
  56.     }
  57.     if ("d" in Options) {
  58.     Dest = "^(" Options["d"] ")$"
  59.     OptGiven = 1
  60.     }
  61.     if ("D" in Options) {
  62.     NotDest = "^(" Options["D"] ")$"
  63.     OptGiven = 1
  64.     }
  65.     if ("t" in Options) {
  66.     TTY = Options["t"]
  67.     if (TTY == "-")
  68.         TTY = "tty\\?\\?"
  69.     TTY = "^(" TTY ")$"
  70.     OptGiven = 1
  71.     }
  72.     if ("T" in Options) {
  73.     notTTY = Options["T"]
  74.     if (notTTY == "-")
  75.         notTTY = "tty\\?\\?"
  76.     notTTY = "^(" notTTY ")$"
  77.     OptGiven = 1
  78.     }
  79.     if ("A" in Options) {
  80.     notApp = "^(" Options["A"] ")$"
  81.     OptGiven = 1
  82.     }
  83.     if ("a" in Options) {
  84.     App = "^(" Options["a"] ")$"
  85.     OptGiven = 1
  86.     }
  87.     if (!OptGiven) {
  88.     NotReq = "^root$"
  89.     Dest = "root"
  90.     }
  91. }
  92.  
  93. {
  94.     split($6,Accts,"-")
  95.     if ((Succ && $4 == "+" || Unsucc && $4 == "-") &&
  96.     (Req == "" || Accts[1] ~ Req) &&
  97.     (NotReq == "" || Accts[1] !~ NotReq) &&
  98.     (Dest == "" || Accts[2] ~ Dest) &&
  99.     (NotDest == "" || Accts[2] !~ NotDest) &&
  100.     (TTY == "" || $5 ~ TTY) &&
  101.     (notTTY == "" || $5 !~ notTTY) &&
  102.     (notApp == "" || $1 !~ notApp) &&
  103.     (App == "" || $1 ~ App))
  104.     print $0
  105. }
  106.  
  107. ### Start of ProcArgs library
  108. # @(#) ProcArgs 1.11 96/12/08
  109. # 92/02/29 john h. dubois iii (john@armory.com)
  110. # 93/07/18 Added "#" arg type
  111. # 93/09/26 Do not count -h against MinArgs
  112. # 94/01/01 Stop scanning at first non-option arg.  Added ">" option type.
  113. #          Removed meaning of "+" or "-" by itself.
  114. # 94/03/08 Added & option and *()< option types.
  115. # 94/04/02 Added NoRCopt to Opts()
  116. # 94/06/11 Mark numeric variables as such.
  117. # 94/07/08 Opts(): Do not require any args if h option is given.
  118. # 95/01/22 Record options given more than once.  Record option num in argv.
  119. # 95/06/08 Added ExclusiveOptions().
  120. # 96/01/20 Let rcfiles be a colon-separated list of filenames.
  121. #          Expand $VARNAME at the start of its filenames.
  122. #          Let varname=0 and -option- turn off an option.
  123. # 96/05/05 Changed meaning of 7th arg to Opts; now can specify exactly how many
  124. #          of the vars should be searched for in the environment.
  125. #          Check for duplicate rcfiles.
  126. # 96/05/13 Return more specific error values.  Note: ProcArgs() and InitOpts()
  127. #          now return various negatives values on error, not just -1, and
  128. #          Opts() may set Err to various positive values, not just 1.
  129. #          Added AllowUnrecOpt.
  130. # 96/05/23 Check type given for & option
  131. # 96/06/15 Re-port to awk
  132. # 96/10/01 Moved file-reading code into ReadConfFile(), so that it can be
  133. #          used by other functions.
  134. # 96/10/15 Added OptChars
  135. # 96/11/01 Added exOpts arg to Opts()
  136. # 96/11/16 Added ; type
  137. # 96/12/08 Added Opt2Set() & Opt2Sets()
  138. # 96/12/27 Added CmdLineOpt()
  139.  
  140. # optlist is a string which contains all of the possible command line options.
  141. # A character followed by certain characters indicates that the option takes
  142. # an argument, with type as follows:
  143. # :    String argument
  144. # ;    Non-empty string argument
  145. # *    Floating point argument
  146. # (    Non-negative floating point argument
  147. # )    Positive floating point argument
  148. # #    Integer argument
  149. # <    Non-negative integer argument
  150. # >    Positive integer argument
  151. # The only difference the type of argument makes is in the runtime argument
  152. # error checking that is done.
  153.  
  154. # The & option is a special case used to get numeric options without the
  155. # user having to give an option character.  It is shorthand for [-+.0-9].
  156. # If & is included in optlist and an option string that begins with one of
  157. # these characters is seen, the value given to "&" will include the first
  158. # char of the option.  & must be followed by a type character other than ":"
  159. # or ";".
  160. # Note that if e.g. &> is given, an option of -.5 will produce an error.
  161.  
  162. # Strings in argv[] which begin with "-" or "+" are taken to be
  163. # strings of options, except that a string which consists solely of "-"
  164. # or "+" is taken to be a non-option string; like other non-option strings,
  165. # it stops the scanning of argv and is left in argv[].
  166. # An argument of "--" or "++" also stops the scanning of argv[] but is removed.
  167. # If an option takes an argument, the argument may either immediately
  168. # follow it or be given separately.
  169. # "-" and "+" options are treated the same.  "+" is allowed because most awks
  170. # take any -options to be arguments to themselves.  gawk 2.15 was enhanced to
  171. # stop scanning when it encounters an unrecognized option, though until 2.15.5
  172. # this feature had a flaw that caused problems in some cases.  See the OptChars
  173. # parameter to explicitly set the option-specifier characters.
  174.  
  175. # If an option that does not take an argument is given,
  176. # an index with its name is created in Options and its value is set to the
  177. # number of times it occurs in argv[].
  178.  
  179. # If an option that does take an argument is given, an index with its name is
  180. # created in Options and its value is set to the value of the argument given
  181. # for it, and Options[option-name,"count"] is (initially) set to the 1.
  182. # If an option that takes an argument is given more than once,
  183. # Options[option-name,"count"] is incremented, and the value is assigned to
  184. # the index (option-name,instance) where instance is 2 for the second occurance
  185. # of the option, etc.
  186. # In other words, the first time an option with a value is encountered, the
  187. # value is assigned to an index consisting only of its name; for any further
  188. # occurances of the option, the value index has an extra (count) dimension.
  189.  
  190. # The sequence number for each option found in argv[] is stored in
  191. # Options[option-name,"num",instance], where instance is 1 for the first
  192. # occurance of the option, etc.  The sequence number starts at 1 and is
  193. # incremented for each option, both those that have a value and those that
  194. # do not.  Options set from a config file have a value of 0 assigned to this.
  195.  
  196. # Options and their arguments are deleted from argv.
  197. # Note that this means that there may be gaps left in the indices of argv[].
  198. # If compress is nonzero, argv[] is packed by moving its elements so that
  199. # they have contiguous integer indices starting with 0.
  200. # Option processing will stop with the first unrecognized option, just as
  201. # though -- was given except that unlike -- the unrecognized option will not be
  202. # removed from ARGV[].  Normally, an error value is returned in this case.
  203. # If AllowUnrecOpt is true, it is not an error for an unrecognized option to
  204. # be found, so the number of remaining arguments is returned instead.
  205. # If OptChars is not a null string, it is the set of characters that indicate
  206. # that an argument is an option string if the string begins with one of the
  207. # characters.  A string consisting solely of two of the same option-indicator
  208. # characters stops the scanning of argv[].  The default is "-+".
  209. # argv[0] is not examined.
  210. # The number of arguments left in argc is returned.
  211. # If an error occurs, the global string OptErr is set to an error message
  212. # and a negative value is returned.
  213. # Current error values:
  214. # -1: option that required an argument did not get it.
  215. # -2: argument of incorrect type supplied for an option.
  216. # -3: unrecognized (invalid) option.
  217. function ProcArgs(argc,argv,OptList,Options,compress,AllowUnrecOpt,OptChars,
  218. ArgNum,ArgsLeft,Arg,ArgLen,ArgInd,Option,Pos,NumOpt,Value,HadValue,specGiven,
  219. NeedNextOpt,GotValue,OptionNum,Escape,dest,src,count,c,OptTerm,OptCharSet)
  220. {
  221. # ArgNum is the index of the argument being processed.
  222. # ArgsLeft is the number of arguments left in argv.
  223. # Arg is the argument being processed.
  224. # ArgLen is the length of the argument being processed.
  225. # ArgInd is the position of the character in Arg being processed.
  226. # Option is the character in Arg being processed.
  227. # Pos is the position in OptList of the option being processed.
  228. # NumOpt is true if a numeric option may be given.
  229.     ArgsLeft = argc
  230.     NumOpt = index(OptList,"&")
  231.     OptionNum = 0
  232.     if (OptChars == "")
  233.     OptChars = "-+"
  234.     while (OptChars != "") {
  235.     c = substr(OptChars,1,1)
  236.     OptChars = substr(OptChars,2)
  237.     OptCharSet[c]
  238.     OptTerm[c c]
  239.     }
  240.     for (ArgNum = 1; ArgNum < argc; ArgNum++) {
  241.     Arg = argv[ArgNum]
  242.     if (length(Arg) < 2 || !((specGiven = substr(Arg,1,1)) in OptCharSet))
  243.         break    # Not an option; quit
  244.     if (Arg in OptTerm) {
  245.         delete argv[ArgNum]
  246.         ArgsLeft--
  247.         break
  248.     }
  249.     ArgLen = length(Arg)
  250.     for (ArgInd = 2; ArgInd <= ArgLen; ArgInd++) {
  251.         Option = substr(Arg,ArgInd,1)
  252.         if (NumOpt && Option ~ /[-+.0-9]/) {
  253.         # If this option is a numeric option, make its flag be & and
  254.         # its option string flag position be the position of & in
  255.         # the option string.
  256.         Option = "&"
  257.         Pos = NumOpt
  258.         # Prefix Arg with a char so that ArgInd will point to the
  259.         # first char of the numeric option.
  260.         Arg = "&" Arg
  261.         ArgLen++
  262.         }
  263.         # Find position of flag in option string, to get its type (if any).
  264.         # Disallow & as literal flag.
  265.         else if (!(Pos = index(OptList,Option)) || Option == "&") {
  266.         if (AllowUnrecOpt) {
  267.             Escape = 1
  268.             break
  269.         }
  270.         else {
  271.             OptErr = "Invalid option: " specGiven Option
  272.             return -3
  273.         }
  274.         }
  275.  
  276.         # Find what the value of the option will be if it takes one.
  277.         # NeedNextOpt is true if the option specifier is the last char of
  278.         # this arg, which means that if the option requires a value it is
  279.         # the next arg.
  280.         if (NeedNextOpt = (ArgInd >= ArgLen)) { # Value is the next arg
  281.         if (GotValue = ArgNum + 1 < argc)
  282.             Value = argv[ArgNum+1]
  283.         }
  284.         else {    # Value is included with option
  285.         Value = substr(Arg,ArgInd + 1)
  286.         GotValue = 1
  287.         }
  288.  
  289.         if (HadValue = AssignVal(Option,Value,Options,
  290.         substr(OptList,Pos + 1,1),GotValue,"",++OptionNum,!NeedNextOpt,
  291.         specGiven)) {
  292.         if (HadValue < 0)    # error occured
  293.             return HadValue
  294.         if (HadValue == 2)
  295.             ArgInd++    # Account for the single-char value we used.
  296.         else {
  297.             if (NeedNextOpt) {    # option took next arg as value
  298.             delete argv[++ArgNum]
  299.             ArgsLeft--
  300.             }
  301.             break    # This option has been used up
  302.         }
  303.         }
  304.     }
  305.     if (Escape)
  306.         break
  307.     # Do not delete arg until after processing of it, so that if it is not
  308.     # recognized it can be left in ARGV[].
  309.     delete argv[ArgNum]
  310.     ArgsLeft--
  311.     }
  312.     if (compress != 0) {
  313.     dest = 1
  314.     src = argc - ArgsLeft + 1
  315.     for (count = ArgsLeft - 1; count; count--) {
  316.         ARGV[dest] = ARGV[src]
  317.         dest++
  318.         src++
  319.     }
  320.     }
  321.     return ArgsLeft
  322. }
  323.  
  324. # Assignment to values in Options[] occurs only in this function.
  325. # Option: Option specifier character.
  326. # Value: Value to be assigned to option, if it takes a value.
  327. # Options[]: Options array to return values in.
  328. # ArgType: Argument type specifier character.
  329. # GotValue: Whether any value is available to be assigned to this option.
  330. # Name: Name of option being processed.
  331. # OptionNum: Number of this option (starting with 1) if set in argv[],
  332. #     or 0 if it was given in a config file or in the environment.
  333. # SingleOpt: true if the value (if any) that is available for this option was
  334. #     given as part of the same command line arg as the option.  Used only for
  335. #     options from the command line.
  336. # specGiven is the option specifier character use, if any (e.g. - or +),
  337. # for use in error messages.
  338. # Global variables: OptErr
  339. # Return value: negative value on error, 0 if option did not require an
  340. # argument, 1 if it did & used the whole arg, 2 if it required just one char of
  341. # the arg.
  342. # Current error values:
  343. # -1: Option that required an argument did not get it.
  344. # -2: Value of incorrect type supplied for option.
  345. # -3: Bad type given for option &
  346. function AssignVal(Option,Value,Options,ArgType,GotValue,Name,OptionNum,
  347. SingleOpt,specGiven,  UsedValue,Err,NumTypes) {
  348.     # If option takes a value...    [
  349.     NumTypes = "*()#<>]"
  350.     if (Option == "&" && ArgType !~ "[" NumTypes) {    # ]
  351.     OptErr = "Bad type given for & option"
  352.     return -3
  353.     }
  354.  
  355.     if (UsedValue = (ArgType ~ "[:;" NumTypes)) {    # ]
  356.     if (!GotValue) {
  357.         if (Name != "")
  358.         OptErr = "Variable requires a value -- " Name
  359.         else
  360.         OptErr = "option requires an argument -- " Option
  361.         return -1
  362.     }
  363.     if ((Err = CheckType(ArgType,Value,Option,Name,specGiven)) != "") {
  364.         OptErr = Err
  365.         return -2
  366.     }
  367.     # Mark this as a numeric variable; will be propogated to Options[] val.
  368.     if (ArgType != ":" && ArgType != ";")
  369.         Value += 0
  370.     if ((Instance = ++Options[Option,"count"]) > 1)
  371.         Options[Option,Instance] = Value
  372.     else
  373.         Options[Option] = Value
  374.     }
  375.     # If this is an environ or rcfile assignment & it was given a value...
  376.     else if (!OptionNum && Value != "") {
  377.     UsedValue = 1
  378.     # If the value is "0" or "-" and this is the first instance of it,
  379.     # do not set Options[Option]; this allows an assignment in an rcfile to
  380.     # turn off an option (for the simple "Option in Options" test) in such
  381.     # a way that it cannot be turned on in a later file.
  382.     if (!(Option in Options) && (Value == "0" || Value == "-"))
  383.         Instance = 1
  384.     else
  385.         Instance = ++Options[Option]
  386.     # Save the value even though this is a flag
  387.     Options[Option,Instance] = Value
  388.     }
  389.     # If this is a command line flag and has a - following it in the same arg,
  390.     # it is being turned off.
  391.     else if (OptionNum && SingleOpt && substr(Value,1,1) == "-") {
  392.     UsedValue = 2
  393.     if (Option in Options)
  394.         Instance = ++Options[Option]
  395.     else
  396.         Instance = 1
  397.     Options[Option,Instance]
  398.     }
  399.     # If this is a flag assignment without a value, increment the count for the
  400.     # flag unless it was turned off.  The indicator for a flag being turned off
  401.     # is that the flag index has not been set in Options[] but it has an
  402.     # instance count.
  403.     else if (Option in Options || !((Option,1) in Options))
  404.     # Increment number of times this flag seen; will inc null value to 1
  405.     Instance = ++Options[Option]
  406.     Options[Option,"num",Instance] = OptionNum
  407.     return UsedValue
  408. }
  409.  
  410. # Option is the option letter
  411. # Value is the value being assigned
  412. # Name is the var name of the option, if any
  413. # ArgType is one of:
  414. # :    String argument
  415. # ;    Non-null string argument
  416. # *    Floating point argument
  417. # (    Non-negative floating point argument
  418. # )    Positive floating point argument
  419. # #    Integer argument
  420. # <    Non-negative integer argument
  421. # >    Positive integer argument
  422. # specGiven is the option specifier character use, if any (e.g. - or +),
  423. # for use in error messages.
  424. # Returns null on success, err string on error
  425. function CheckType(ArgType,Value,Option,Name,specGiven,  Err,ErrStr) {
  426.     if (ArgType == ":")
  427.     return ""
  428.     if (ArgType == ";") {
  429.     if (Value == "")
  430.         Err = "must be a non-empty string"
  431.     }
  432.     # A number begins with optional + or -, and is followed by a string of
  433.     # digits or a decimal with digits before it, after it, or both
  434.     else if (Value !~ /^[-+]?([0-9]+|[0-9]*\.[0-9]+|[0-9]+\.)$/)
  435.     Err = "must be a number"
  436.     else if (ArgType ~ "[#<>]" && Value ~ /\./)
  437.     Err = "may not include a fraction"
  438.     else if (ArgType ~ "[()<>]" && Value < 0)
  439.     Err = "may not be negative"
  440.     # (
  441.     else if (ArgType ~ "[)>]" && Value == 0)
  442.     Err = "must be a positive number"
  443.     if (Err != "") {
  444.     ErrStr = "Bad value \"" Value "\".  Value assigned to "
  445.     if (Name != "")
  446.         return ErrStr "variable " substr(Name,1,1) " " Err
  447.     else {
  448.         if (Option == "&")
  449.         Option = Value
  450.         return ErrStr "option " specGiven substr(Option,1,1) " " Err
  451.     }
  452.     }
  453.     else
  454.     return ""
  455. }
  456.  
  457. # Note: only the above functions are needed by ProcArgs.
  458. # The rest of these functions call ProcArgs() and also do other
  459. # option-processing stuff.
  460.  
  461. # Opts: Process command line arguments.
  462. # Opts processes command line arguments using ProcArgs()
  463. # and checks for errors.  If an error occurs, a message is printed
  464. # and the program is exited.
  465. #
  466. # Input variables:
  467. # Name is the name of the program, for error messages.
  468. # Usage is a usage message, for error messages.
  469. # OptList the option description string, as used by ProcArgs().
  470. # MinArgs is the minimum number of non-option arguments that this
  471. # program should have, non including ARGV[0] and +h.
  472. # If the program does not require any non-option arguments,
  473. # MinArgs should be omitted or given as 0.
  474. # rcFiles, if given, is a colon-seprated list of filenames to read for
  475. # variable initialization.  If a filename begins with ~/, the ~ is replaced
  476. # by the value of the environment variable HOME.  If a filename begins with
  477. # $, the part from the character after the $ up until (but not including)
  478. # the first character not in [a-zA-Z0-9_] will be searched for in the
  479. # environment; if found its value will be substituted, if not the filename will
  480. # be discarded.
  481. # rcfiles are read in the order given.
  482. # Values given in them will not override values given on the command line,
  483. # and values given in later files will not override those set in earlier
  484. # files, because AssignVal() will store each with a different instance index.
  485. # The first instance of each variable, either on the command line or in an
  486. # rcfile, will be stored with no instance index, and this is the value
  487. # normally used by programs that call this function.
  488. # VarNames is a comma-separated list of variable names to map to options,
  489. # in the same order as the options are given in OptList.
  490. # If EnvSearch is given and nonzero, the first EnvSearch variables will also be
  491. # searched for in the environment.  If set to -1, all values will be searched
  492. # for in the environment.  Values given in the environment will override
  493. # those given in the rcfiles but not those given on the command line.
  494. # NoRCopt, if given, is an additional letter option that if given on the
  495. # command line prevents the rcfiles from being read.
  496. # See ProcArgs() for a description of AllowUnRecOpt and optChars, and
  497. # ExclusiveOptions() for a description of exOpts.
  498. # Special options:
  499. # If x is made an option and is given, some debugging info is output.
  500. # h is assumed to be the help option.
  501.  
  502. # Global variables:
  503. # The command line arguments are taken from ARGV[].
  504. # The arguments that are option specifiers and values are removed from
  505. # ARGV[], leaving only ARGV[0] and the non-option arguments.
  506. # The number of elements in ARGV[] should be in ARGC.
  507. # After processing, ARGC is set to the number of elements left in ARGV[].
  508. # The option values are put in Options[].
  509. # On error, Err is set to a positive integer value so it can be checked for in
  510. # an END block.
  511. # Return value: The number of elements left in ARGV is returned.
  512. # Must keep OptErr global since it may be set by InitOpts().
  513. function Opts(Name,Usage,OptList,MinArgs,rcFiles,VarNames,EnvSearch,NoRCopt,
  514. AllowUnrecOpt,optChars,exOpts,  ArgsLeft,e) {
  515.     if (MinArgs == "")
  516.     MinArgs = 0
  517.     ArgsLeft = ProcArgs(ARGC,ARGV,OptList NoRCopt,Options,1,AllowUnrecOpt,
  518.     optChars)
  519.     if (ArgsLeft < (MinArgs+1) && !("h" in Options)) {
  520.     if (ArgsLeft >= 0) {
  521.         OptErr = "Not enough arguments"
  522.         Err = 4
  523.     }
  524.     else
  525.         Err = -ArgsLeft
  526.     printf "%s: %s.\nUse -h for help.\n%s\n",
  527.     Name,OptErr,Usage > "/dev/stderr"
  528.     exit 1
  529.     }
  530.     if (rcFiles != "" && (NoRCopt == "" || !(NoRCopt in Options)) &&
  531.     (e = InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch)) < 0)
  532.     {
  533.     print Name ": " OptErr ".\nUse -h for help." > "/dev/stderr"
  534.     Err = -e
  535.     exit 1
  536.     }
  537.     if ((exOpts != "") && ((OptErr = ExclusiveOptions(exOpts,Options)) != ""))
  538.     {
  539.     printf "%s: Error: %s\n",Name,OptErr > "/dev/stderr"
  540.     Err = 1
  541.     exit 1
  542.     }
  543.     return ArgsLeft
  544. }
  545.  
  546. # ReadConfFile(): Read a file containing var/value assignments, in the form
  547. # <variable-name><assignment-char><value>.
  548. # Whitespace (spaces and tabs) around a variable (leading whitespace on the
  549. # line and whitespace between the variable name and the assignment character) 
  550. # is stripped.  Lines that do not contain an assignment operator or which
  551. # contain a null variable name are ignored, other than possibly being noted in
  552. # the return value.  If more than one assignment is made to a variable, the
  553. # first assignment is used.
  554. # Input variables:
  555. # File is the file to read.
  556. # Comment is the line-comment character.  If it is found as the first non-
  557. #     whitespace character on a line, the line is ignored.
  558. # Assign is the assignment string.  The first instance of Assign on a line
  559. #     separates the variable name from its value.
  560. # If StripWhite is true, whitespace around the value (whitespace between the
  561. #     assignment char and trailing whitespace on the line) is stripped.
  562. # VarPat is a pattern that variable names must match.  
  563. #     Example: "^[a-zA-Z][a-zA-Z0-9]+$"
  564. # If FlagsOK is true, variables are allowed to be "set" by being put alone on
  565. #     a line; no assignment operator is needed.  These variables are set in
  566. #     the output array with a null value.  Lines containing nothing but
  567. #     whitespace are still ignored.
  568. # Output variables:
  569. # Values[] contains the assignments, with the indexes being the variable names
  570. #     and the values being the assigned values.
  571. # Lines[] contains the line number that each variable occured on.  A flag set
  572. #     is record by giving it an index in Lines[] but not in Values[].
  573. # Return value:
  574. # If any errors occur, a string consisting of descriptions of the errors
  575. # separated by newlines is returned.  In no case will the string start with a
  576. # numeric value.  If no errors occur,  the number of lines read is returned.
  577. function ReadConfigFile(Values,Lines,File,Comment,Assign,StripWhite,VarPat,
  578. FlagsOK,
  579. Line,Status,Errs,AssignLen,LineNum,Var,Val) {
  580.     if (Comment != "")
  581.     Comment = "^" Comment
  582.     AssignLen = length(Assign)
  583.     if (VarPat == "")
  584.     VarPat = "."    # null varname not allowed
  585.     while ((Status = (getline Line < File)) == 1) {
  586.     LineNum++
  587.     sub("^[ \t]+","",Line)
  588.     if (Line == "")        # blank line
  589.         continue
  590.     if (Comment != "" && Line ~ Comment)
  591.         continue
  592.     if (Pos = index(Line,Assign)) {
  593.         Var = substr(Line,1,Pos-1)
  594.         Val = substr(Line,Pos+AssignLen)
  595.         if (StripWhite) {
  596.         sub("^[ \t]+","",Val)
  597.         sub("[ \t]+$","",Val)
  598.         }
  599.     }
  600.     else {
  601.         Var = Line    # If no value, var is entire line
  602.         Val = ""
  603.     }
  604.     if (!FlagsOK && Val == "") {
  605.         Errs = Errs \
  606.         sprintf("\nBad assignment on line %d of file %s: %s",
  607.         LineNum,File,Line)
  608.         continue
  609.     }
  610.     sub("[ \t]+$","",Var)
  611.     if (Var !~ VarPat) {
  612.         Errs = Errs sprintf("\nBad variable name on line %d of file %s: %s",
  613.         LineNum,File,Var)
  614.         continue
  615.     }
  616.     if (!(Var in Lines)) {
  617.         Lines[Var] = LineNum
  618.         if (Pos)
  619.         Values[Var] = Val
  620.     }
  621.     }
  622.     if (Status)
  623.     Errs = Errs "\nCould not read file " File
  624.     close(File)
  625.     return Errs == "" ? LineNum : substr(Errs,2)    # Skip first newline
  626. }
  627.  
  628. # Variables:
  629. # Data is stored in Options[].
  630. # rcFiles, OptList, VarNames, and EnvSearch are as as described for Opts().
  631. # Global vars:
  632. # Sets OptErr.  Uses ENVIRON[].
  633. # If anything is read from any of the rcfiles, sets READ_RCFILE to 1.
  634. function InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch,
  635. Line,Var,Pos,Vars,Map,CharOpt,NumVars,TypesInd,Types,Type,Ret,i,rcFile,
  636. fNames,numrcFiles,filesRead,Err,Values,retStr) {
  637.     split("",filesRead,"")    # make awk know this is an array
  638.     NumVars = split(VarNames,Vars,",")
  639.     TypesInd = Ret = 0
  640.     if (EnvSearch == -1)
  641.     EnvSearch = NumVars
  642.     for (i = 1; i <= NumVars; i++) {
  643.     Var = Vars[i]
  644.     CharOpt = substr(OptList,++TypesInd,1)
  645.     if (CharOpt ~ "^[:;*()#<>&]$")
  646.         CharOpt = substr(OptList,++TypesInd,1)
  647.     Map[Var] = CharOpt
  648.     Types[Var] = Type = substr(OptList,TypesInd+1,1)
  649.     # Do not overwrite entries from environment
  650.     if (i <= EnvSearch && Var in ENVIRON &&
  651.     (Err = AssignVal(CharOpt,ENVIRON[Var],Options,Type,1,Var,0)) < 0)
  652.         return Err
  653.     }
  654.  
  655.     numrcFiles = split(rcFiles,fNames,":")
  656.     for (i = 1; i <= numrcFiles; i++) {
  657.     rcFile = fNames[i]
  658.     if (rcFile ~ "^~/")
  659.         rcFile = ENVIRON["HOME"] substr(rcFile,2)
  660.     else if (rcFile ~ /^\$/) {
  661.         rcFile = substr(rcFile,2)
  662.         match(rcFile,"^[a-zA-Z0-9_]*")
  663.         envvar = substr(rcFile,1,RLENGTH)
  664.         if (envvar in ENVIRON)
  665.         rcFile = ENVIRON[envvar] substr(rcFile,RLENGTH+1)
  666.         else
  667.         continue
  668.     }
  669.     if (rcFile in filesRead)
  670.         continue
  671.     # rcfiles are liable to be given more than once, e.g. UHOME and HOME
  672.     # may be the same
  673.     filesRead[rcFile]
  674.     if ("x" in Options)
  675.         printf "Reading configuration file %s\n",rcFile > "/dev/stderr"
  676.     retStr = ReadConfigFile(Values,Lines,rcFile,"#","=",0,"",1)
  677.     if (retStr > 0)
  678.         READ_RCFILE = 1
  679.     else if (ret != "") {
  680.         OptErr = retStr
  681.         Ret = -1
  682.     }
  683.     for (Var in Lines)
  684.         if (Var in Map) {
  685.         if ((Err = AssignVal(Map[Var],
  686.         Var in Values ? Values[Var] : "",Options,Types[Var],
  687.         Var in Values,Var,0)) < 0)
  688.             return Err
  689.         }
  690.         else {
  691.         OptErr = sprintf(\
  692.         "Unknown var \"%s\" assigned to on line %d\nof file %s",Var,
  693.         Lines[Var],rcFile)
  694.         Ret = -1
  695.         }
  696.     }
  697.  
  698.     if ("x" in Options)
  699.     for (Var in Map)
  700.         if (Map[Var] in Options)
  701.         printf "(%s) %s=%s\n",Map[Var],Var,Options[Map[Var]] > \
  702.         "/dev/stderr"
  703.         else
  704.         printf "(%s) %s not set\n",Map[Var],Var > "/dev/stderr"
  705.     return Ret
  706. }
  707.  
  708. # OptSets is a semicolon-separated list of sets of option sets.
  709. # Within a list of option sets, the option sets are separated by commas.  For
  710. # each set of sets, if any option in one of the sets is in Options[] AND any
  711. # option in one of the other sets is in Options[], an error string is returned.
  712. # If no conflicts are found, nothing is returned.
  713. # Example: if OptSets = "ab,def,g;i,j", an error will be returned due to
  714. # the exclusions presented by the first set of sets (ab,def,g) if:
  715. # (a or b is in Options[]) AND (d, e, or f is in Options[]) OR
  716. # (a or b is in Options[]) AND (g is in Options) OR
  717. # (d, e, or f is in Options[]) AND (g is in Options)
  718. # An error will be returned due to the exclusions presented by the second set
  719. # of sets (i,j) if: (i is in Options[]) AND (j is in Options[]).
  720. # todo: make options given on command line unset options given in config file
  721. # todo: that they conflict with.
  722. function ExclusiveOptions(OptSets,Options,
  723. Sets,SetSet,NumSets,Pos1,Pos2,Len,s1,s2,c1,c2,ErrStr,L1,L2,SetSets,NumSetSets,
  724. SetNum,OSetNum) {
  725.     NumSetSets = split(OptSets,SetSets,";")
  726.     # For each set of sets...
  727.     for (SetSet = 1; SetSet <= NumSetSets; SetSet++) {
  728.     # NumSets is the number of sets in this set of sets.
  729.     NumSets = split(SetSets[SetSet],Sets,",")
  730.     # For each set in a set of sets except the last...
  731.     for (SetNum = 1; SetNum < NumSets; SetNum++) {
  732.         s1 = Sets[SetNum]
  733.         L1 = length(s1)
  734.         for (Pos1 = 1; Pos1 <= L1; Pos1++)
  735.         # If any of the options in this set was given, check whether
  736.         # any of the options in the other sets was given.  Only check
  737.         # later sets since earlier sets will have already been checked
  738.         # against this set.
  739.         if ((c1 = substr(s1,Pos1,1)) in Options)
  740.             for (OSetNum = SetNum+1; OSetNum <= NumSets; OSetNum++) {
  741.             s2 = Sets[OSetNum]
  742.             L2 = length(s2)
  743.             for (Pos2 = 1; Pos2 <= L2; Pos2++)
  744.                 if ((c2 = substr(s2,Pos2,1)) in Options)
  745.                 ErrStr = ErrStr "\n"\
  746.                 sprintf("Cannot give both %s and %s options.",
  747.                 c1,c2)
  748.             }
  749.     }
  750.     }
  751.     if (ErrStr != "")
  752.     return substr(ErrStr,2)
  753.     return ""
  754. }
  755.  
  756. # The value of each instance of option Opt that occurs in Options[] is made an
  757. # index of Set[].
  758. # The return value is the number of instances of Opt in Options.
  759. function Opt2Set(Options,Opt,Set,  count) {
  760.     if (!(Opt in Options))
  761.     return 0
  762.     Set[Options[Opt]]
  763.     count = Options[Opt,"count"]
  764.     for (; count > 1; count--)
  765.     Set[Options[Opt,count]]
  766.     return count
  767. }
  768.  
  769. # The value of each instance of option Opt that occurs in Options[] that
  770. # begins with "!" is made an index of nSet[] (with the ! stripped from it).
  771. # Other values are made indexes of Set[].
  772. # The return value is the number of instances of Opt in Options.
  773. function Opt2Sets(Options,Opt,Set,nSet,  count,aSet,ret) {
  774.     ret = Opt2Set(Options,Opt,aSet)
  775.     for (value in aSet)
  776.     if (substr(value,1,1) == "!")
  777.         nSet[substr(value,2)]
  778.     else
  779.         Set[value]
  780.     return ret
  781. }
  782.  
  783. # Returns true if option Opt was given on the command line.
  784. function CmdLineOpt(Options,Opt,  i) {
  785.     for (i = 1; (Opt,"num",i) in Options; i++)
  786.     if (Options[Opt,"num",i] != 0)
  787.         return 1
  788.     return 0
  789. }
  790. ### End of ProcArgs library
  791.